import linkCard from './components/linkCard.vue'
import api from '../../api/index.js'
import { getIconLinks, getTabsTitle } from './authLinks.js'
import getLocationAuth from '@/utils/getLocationAuth.js'

import iNav from './components/nav.vue'

// 不同权限的tab组件列表
import carStoreList from './components/carStoreList.vue'
import curingList from './components/curingList.vue'
import franchisee from './components/franchisee.vue'

export default {
  components: {
    iNav,
    linkCard,
    carStoreList,
    curingList,
    franchisee
  },
  data() {
    return {
      isPageShow: false,
      offTop: 0, //吸顶高度
      auth: '',
      stickyJudgment: false, //筛选置顶判断
      province: '', //省份
      city: '', //城市
      scrollTop: 0,
      banners: [], //首页banner
      // 卖车的banner
      carStoreFactoryBanners: [
        'https://files.yzsheng.com/bussiness/imgs/banner/carStoreFactory/banner1.png',
        'https://files.yzsheng.com/bussiness/imgs/banner/carStoreFactory/banner2.png',
        'https://files.yzsheng.com/bussiness/imgs/banner/carStoreFactory/banner3.png',
        'https://files.yzsheng.com/bussiness/imgs/banner/carStoreFactory/banner4.png',
        'https://files.yzsheng.com/bussiness/imgs/banner/carStoreFactory/banner5.png',
      ],
      // 养护的banner
      beautyStoreRepairStoreBanners: [
        'https://files.yzsheng.com/bussiness/imgs/banner/beautyStoreRepairStore/banner1.png',
        'https://files.yzsheng.com/bussiness/imgs/banner/beautyStoreRepairStore/banner2.png',
        'https://files.yzsheng.com/bussiness/imgs/banner/beautyStoreRepairStore/banner3.png',
        'https://files.yzsheng.com/bussiness/imgs/banner/beautyStoreRepairStore/banner4.png',
        'https://files.yzsheng.com/bussiness/imgs/banner/beautyStoreRepairStore/banner5.png',
      ],
      bannerCurrent: 0, // banner当前
      bannerswiperCurrent: 0,
      // 货源服务 - 版块链接图标，文字
      linkDatas: [
        {
          icon: 'iconshouye-cheyuan',
          label: '车源',
          path: '/pages_carSource/optionsCar/optionsCar',
          color: '#fa763e',
        },
        {
          icon: 'iconshouye-xunche',
          label: '寻车',
          path: '/pages_findCar/findtheCar/findtheCar',
          color: '#ffc20e',
        },
        {
          icon: 'iconshouye-meihubaojingpin_1',
          label: '美护保精品',
          path: '/pages_qualityGoods/beauty/beauty',
          color: '#43a0fc',
        },
        {
          icon: 'iconshouye-xunpeijian',
          label: '寻配件',
          path: '/pages_findAccessory/accessoryIndex/accessory_index',
          color: '#f96a56',
        },
        {
          icon: 'iconzichanguanli',
          label: '发起交易',
          path:
            '/pages_order/securedTransactions/securedTransactions?page=index',
          color: '#0FB97F',
        },
        {
          icon: 'iconzichanguanli',
          label: '物流',
          path: '',
          color: '#00CB86',
        },
        {
          icon: 'iconzichanguanli',
          label: '垫资',
          path: '',
          color: '#FF9C00',
        },
        {
          icon: 'iconshouye-gouchejisuanqi',
          label: '购车计算器',
          path: '',
          color: '#FFA42C',
        },
      ],
      text: [],

      storeId: '', // 记录的店铺id
      switchCityShow: false, // 控制显示切换城市弹框

      // 临时储存定位信息，确认切换城市就从此变量获取
      tempAddressData: {
        address: {
          city: '成都市',
        },
      },

      //是否加载页面
      isLoadingPage: false,
    }
  },

  computed: {
    tabHeight() {
      return uni.getSystemInfoSync().windowHeight
    },
  },

  onLoad() {
    this.location()
    this.init() // 初始化加载首页逻辑

    // 登录成功后会触发 SDK_READY 事件，该事件触发后，可正常使用 SDK 接口
    this.tim.on(this.$TIM.EVENT.SDK_READY, this.onReadyStateUpdate, this)
    // 收到新消息
    this.tim.on(this.$TIM.EVENT.MESSAGE_RECEIVED, this.onReceiveMessage)
    // 会话列表更新
    this.tim.on(this.$TIM.EVENT.CONVERSATION_LIST_UPDATED, event => {
      this.$store.commit('news/updateConversationList', event.data)
    })

    //登录tim
    this.loginTim()

    this.storeId = this.$store.state.userInfoDetail.store.storeId
    // #ifdef APP-PLUS
    this.loginPush()
    // #endif
  },

  onShow() {
    this.city = this.$store.state.city
    // 如果发现店铺id不相等，则需要重新加载首页的数据
    if (this.storeId !== this.$store.state.userInfoDetail.store.storeId) {
      this.init() // 初始化加载首页逻辑
    }
    if (this.auth === 'BeautyStore') {
      this.$nextTick(() => {
        this.$refs['beautyStore'].handleAuthContent()
      })
    } else {
      this.init()
    }
    if(this.$refs.franchisee){
      this.$refs.franchisee.getSelfServiceCarHomePage()
    }

    // this.location()
    // console.log(this.auth,'进入index')
  },

  onReady() {
    // Partner
    // this.auth !== 'BeautyStore' && this.auth !== 'League' && this.auth !== 'Agency' && this.auth !== 'Construction' && this.auth !== 'Place' && this.auth !== 'Equipment' && this.auth !== 'ChildEquipment' && this.auth !=='Resource'
    if (this.auth !== 'BeautyStore' && this.auth !== 'Partner' && this.auth !== 'League' && this.auth !== 'Agency') {
      // console.log('ready')
      this.$nextTick(() => {
        this.$refs.nav.getHeight(data => {
          this.offTop = data
        })
      })
    }
  },

  methods: {
    loginPush(){

      // 更新用户推送设备
      this.$api.user.AddOrEditUniPush({
			  type: 'login',
			  cid: plus.push.getClientInfo().clientid,
			  platform: uni.getSystemInfoSync().platform,
        storeId: this.$store.state.userInfoDetail.store.storeId,
        phone: this.$store.state.user.userInfo.mobile
      }).then(res => {
			  console.log(res)
      })

    },
    // 初始化加载首页时
    init() {
      // #ifdef APP-NVUE
      // this.iStatusBarHeight = uni.getSystemInfoSync().statusBarHeight
      // #endif
      // 检查本地储存是否有用户信息，如果有，就加到vuex里
      if (uni.getStorageSync('userInfoDetail')) {
        let userInfoDetail = uni.getStorageSync('userInfoDetail')
        this.$store.commit('setUserInfoDetail', userInfoDetail)
      }

      this.auth = uni.getStorageSync('Ztc_B_USER_INFO').permious
	   // this.auth = 'CarStore'
      if(this.auth==='League'|| this.auth === 'Partner' || this.auth === 'League' || this.auth === 'Agency'){
			  uni.hideTabBar({
				  animation: true
			  })
      }else{
        uni.showTabBar({
          animation: true
        })
      }
      this.isLoadingPage = true
      // this.auth = 'CarStore'
      this.linkDatas = getIconLinks(this.auth) // 显示不同icon链接内容

      // 处理banner图
      const banners = new Map([
        ['CarStore', this.carStoreFactoryBanners],
        ['Factory', this.carStoreFactoryBanners],
        ['BeautyStore', this.beautyStoreRepairStoreBanners],
        ['RepairStore', this.beautyStoreRepairStoreBanners],
      ])
      this.banners = banners.get(this.auth)
    },
    //车源懒加载
    carLoad() {
      //车源列表
      this.status = 'loading'
    },

    // 监听swiper
    swiperChange(e) {
      this.bannerswiperCurrent = e.detail.current
    },

    //城市选择
    cityChoice(id) {
      // console.log(id)
    },

    //定位
    location() {
      uni.getLocation({
        type: 'gcj02',
        geocode: true,
        success: res => {
          this.tempAddressData = res // 存放到临时变量
          this.handleCity(res.address) // 调用处理城市定位和切换的方法
        },
        fail: err => {
          console.log('获取定位失败', err)
          getLocationAuth() // 获取系统定位权限
        },
      })
    },

    // 从本地缓存获取城市
    setAddressCity() {
      let p = uni.getStorageSync('province')
      let c = uni.getStorageSync('city')
      // 把定位省市存到vuex-store
      this.$store.dispatch('changeAddress', {
        province: p,
        city: c,
      })
    },

    // 判断定位城市是否为上一次定位的城市
    handleCity(data) {
      let city = uni.getStorageSync('city')
      // 用户第一次打开使用APP，本地如果没有缓存城市，则缓存一下
      if (!city) {
        uni.setStorageSync('province', data.province)
        uni.setStorageSync('city', data.city)
        uni.setStorageSync('lat', this.tempAddressData.latitude)
        uni.setStorageSync('lon', this.tempAddressData.longitude)

        // 把定位省市存到vuex-store
        this.$store.dispatch('changeAddress', data)
        return
      } else {
        this.setAddressCity() // 从本地缓存获取城市
      }
      // 存放定位经纬度到vuex-store
      this.$store.dispatch('changeLatitude', this.tempAddressData.latitude)
      this.$store.dispatch('changeLongitude', this.tempAddressData.longitude)

      // 如果定位城市与本地缓存城市一致，不执行后面操作
      if (city === data.city) return

      // 如果城市不一致，提示用户是否切换城市
      // 如果城市不一致，提示用户是否切换城市
      this.switchCityShow = true
    },

    // 切换城市
    handleSwitchCity(e) {
      if (e) {
        uni.setStorageSync('province', this.tempAddressData.address.province)
        uni.setStorageSync('city', this.tempAddressData.address.city)
        uni.setStorageSync('lat', this.tempAddressData.latitude)
        uni.setStorageSync('lon', this.tempAddressData.longitude)
        // 把定位省市存到vuex-store
        this.$store.dispatch('changeAddress', this.tempAddressData.address)

        // 存放定位经纬度到vuex-store
        this.$store.dispatch('changeLatitude', this.tempAddressData.latitude)
        this.$store.dispatch('changeLongitude', this.tempAddressData.longitude)
      }
      this.switchCityShow = false
    },

    // 扫码
    scanQRcode() {
      // #ifdef APP-PLUS
      var appid = plus.runtime.appid
      // console.log('应用的 appid 为：' + appid)
      // #endif
    },

    onReadyStateUpdate({ name }) {
      const isSDKReady = name === this.$TIM.EVENT.SDK_READY ? true : false
      //自动监听并更新 sdk 的ready 状态 （未登录是 notReady  登录后是ready）
      this.$store.commit('news/toggleIsSDKReady', isSDKReady)
      this.updateMyProfile()
      //sdk ready 后  肯定完成了登录操作    这里可以获取用户存储在im的基础信息/离线消息/黑名单列表
    },

    onReceiveMessage({ data: messageList }) {
      // this.handleAt(messageList);
      this.$store.commit('news/pushCurrentMessageList', messageList)
    },

    loginTim() {
      // console.log(this.$store.state.userInfoDetail.store)
      if (!this.$store.state.userInfoDetail.store) {
        // console.log(1)
        this.getUserInfo()
      } else {
        // console.log(2)
        this.$api.news
          .getTimInfo({
            storeId: this.$store.state.userInfoDetail.store.storeId,
          })
          .then(res => {
            this.$store.commit('news/setUer', {
              userId: res.data.userid,
              user:
                res.data.username !== null
                  ? res.data.username
                  : this.$store.state.userInfoDetail.store.storeName,
              img: res.data.img,
              userSig: res.data.usersig,
            })
            this.timLogin()
          })
      }
    },

    getUserInfo() {
      this.$api.user.getUserInfo().then(async datas => {
        // console.log(1164, datas)
        this.$store.commit('setUserInfoDetail', datas.data)
        try {
          const res = await this.$api.news.getTimInfo({
            storeId: datas.data.store.storeId,
          })
          this.$store.commit('news/setUer', {
            userId: res.data.userid,
            user:
              res.data.username !== null
                ? datas.data.store.storeName
                : this.$store.state.userInfoDetail.store.storeName,
            img: res.data.img,
            userSig: res.data.usersig,
          })
          this.timLogin()
        } catch (e) {
          //TODO handle the exception
        }
      })
    },

    timLogin() {
      // console.log('登录tim:', this.$store.state.news.userId)
      this.tim
        .login({
          userID: this.$store.state.news.userId,
          userSig: this.$store.state.news.userSig,
        })
        .then(res => {
          //登录成功后 更新登录状态
          this.$store.commit('news/toggleIsLogin', true)
          //tim 返回的用户信息
          // uni.setStorageSync('userTIMInfo', JSON.stringify(res.data))
          // this.$store.commit('createConversationActive', item.Tid)
        })
        .catch(err => {
          console.warn('login error:', err) // 登录失败的相关信息
        })
    },

    //更新tim信息
    updateMyProfile() {
      // 修改个人标配资料
      let promise = this.tim.updateMyProfile({
        nick: this.$store.state.userInfoDetail.store.storeName,
        allowType: this.$TIM.TYPES.ALLOW_TYPE_ALLOW_ANY,
      })
      promise
        .then(function (imResponse) {
          // console.log(imResponse.data) // 更新资料成功
        })
        .catch(function (imError) {
          console.warn('updateMyProfile error:', imError) // 更新资料失败的相关信息
        })
    },
  },
}
